package co.fitstart.admin.web.controller.system;


import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Preloading;
import co.fitstart.admin.service.CoachService;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.service.SiteService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.entity.coach.CoachSettlement;
import co.fitstart.entity.coach.PrincipalReportRelation;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.principal.Profile;
import co.fitstart.entity.principal.SpecialTags;
import co.fitstart.entity.site.Site;


/**
 * @author mohanlan
 */
@Controller
@RequestMapping("/principals")
@MenuSetting("menu-system")
public class PrincipalEditController {
    
    private static Logger logger = LoggerFactory.getLogger(PrincipalEditController.class);
    
    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    private CoachService coachService;
    
    @Autowired
    private SiteService siteService;
    
    /**
     * display principal edit panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable Long id) {
        
        ModelAndView modelAndView = new ModelAndView("system/principal/principal-edit");
        
        Principal principal = principalService.load(Principal.class, id);
        modelAndView.addObject("principal", principal);
        
        return modelAndView; 
    }
    
    /**
     * edit principal
     * @param principal
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
    public @ResponseBody String onEdit(@Preloading Principal principal) {
        
        Result result = new Result();
        
        try {
            
            principalService.update(principal);
        
            result.success().message("修改账号成功！");
            
        } catch(Exception e) {
            
            result.fail().message("修改账号失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * display principal profile edit panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/profile", method = RequestMethod.GET)
    public ModelAndView editProfile(@PathVariable Long id) {
        
        ModelAndView modelAndView = new ModelAndView("system/principal/principal-profile-edit");
        
        Principal principal = principalService.load(Principal.class, id);
        modelAndView.addObject("principal", principal);
        
        return modelAndView; 
    }
    
    /**
     * edit principal profile
     * 
     * @param principal
     * @return
     */
    @RequestMapping(value = "/{id}/profile", method = RequestMethod.PATCH)
    public @ResponseBody String onEditProfile(@Preloading Principal principal) {
        
        Result result = new Result();
        
        try {
            
            principalService.update(principal);
        
            result.success().message("修改个人信息成功！");
            
        } catch(Exception e) {
            
            result.fail().message("修改个人信息失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    

    /**
     * display principal profile edit panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/special-tags", method = RequestMethod.GET)
    public ModelAndView specialTags(@PathVariable Long id) {
        
        ModelAndView modelAndView = new ModelAndView("system/principal/principal-specialtags-edit");
        
        Principal principal = principalService.load(Principal.class, id);
        modelAndView.addObject("principal", principal);
        
        return modelAndView; 
    }
    
    @RequestMapping(value = "/{id}/special-tags", method = RequestMethod.PATCH)
    public @ResponseBody String onSpecialTags(@PathVariable Long id,
                                              @RequestParam(value = "specialTags", required = false) List<SpecialTags> tags) {
        
        Result result = new Result();
        
        try {
            
            Principal principal = principalService.load(Principal.class, id);
            Profile profile = principal.getProfile();
            if(profile == null) {
                profile = new Profile();
            }
            profile.editSpecilTags(tags);
            principalService.update(principal.editProfile(profile));
        
            result.success().message("修改特色课标签成功！");
            
        } catch(Exception e) {
            
            result.fail().message("修改特色课标签失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * display edit avatar panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/avatar", method = RequestMethod.GET)
    public ModelAndView editAvatar(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("system/principal/principal-avatar-edit");
        
        Principal principal = principalService.load(Principal.class, id);
        
        modelAndView.addObject("principalId", id);
        
        // FIXME principal.getProfile().getAvatar() has problem
        String avatar = principal.getProfile() == null ? "" : principal.getProfile().getAvatar();
        modelAndView.addObject("avatar", avatar);
        
        return modelAndView; 
    }
    
    /**
     * reset password
     * 
     * @param id
     * @param avatar
     * @return
     */
    @RequestMapping(value = "/{id}/avatar", method = RequestMethod.PATCH)
    public @ResponseBody String onEditAvatar(@PathVariable Long id, @RequestParam("avatar") String avatar) {
        Result result = new Result();
        try {
            
            Principal principal = principalService.load(Principal.class, id);
            
            principalService.update(principal.editAvatar(avatar));
            
            result.success().message("上传头像成功！");
            
        } catch (Exception e) {
            
        	logger.error("onEditAvatar error() ", e);
        	
            result.fail().message("上传头像失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
 
    /**
     * change principal status
     * 
     * @param principalId
     * @return
     */
    @RequestMapping("/{principalId}/change-status")
    public ModelAndView changeStatus(@PathVariable("principalId") Long principalId) {
        
        ModelAndView modelAndView = new ModelAndView("system/principal/principal-change-status");
        
        modelAndView.addObject("principalId", principalId);

        return modelAndView;
    }
    
    /**
     * On change principal status
     * 
     * @param principalId
     * @return
     */
    @RequestMapping(value = "/{principalId}/change-status", method = RequestMethod.PATCH)
    public @ResponseBody String onChangeStatus(@PathVariable("principalId") Long principalId) {
        
        Result result = new Result();
        
        try {
            
            Principal principal = principalService.load(Principal.class, principalId);
            principalService.changeStatus(principal);
            
            result.success().message("更改用户锁定状态成功");
        } catch(BusinessException e) {
            result.fail().message(e.getMessage());
        } catch(Exception e) {
            
            result.fail().message("更改用户锁定状态失败");
        }
        
        return JsonUtils.toJsonString(result);

    }
    
    /**
     * display reset password panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/reset-password", method = RequestMethod.GET)
    public ModelAndView resetPassword(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("system/principal/principal-reset-password");
        modelAndView.addObject("id", id);
        return modelAndView; 
    }
    
    /**
     * reset password
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/reset-password", method = RequestMethod.PATCH)
    public @ResponseBody String onResetPassword(@PathVariable("id") Long id) {
        Result result = new Result();
        try {
            
            Principal principal = principalService.get(Principal.class, id);
            
            principalService.resetPassword(principal);
            
            result.success().message("重置密码成功！");
            
        } catch (Exception e) {
            
            result.fail().message("重置密码失败！");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * View coach settlements
     * 
     * @param coachId
     * @param settlementId
     * @return
     */
    @RequestMapping(value = "/{coachId}/settlements/{settlementId}", method = RequestMethod.GET)
    public ModelAndView editSettlement(@PathVariable("coachId") Long coachId,
                                       @PathVariable("settlementId") Long settlementId) {
        
        ModelAndView modelAndView = new ModelAndView("system/principal/coach-settlement-edit");
        
        CoachSettlement settlement = coachService.loadSettlement(settlementId);
        
        modelAndView.addObject("coachId", coachId);
        modelAndView.addObject("settlement", settlement);
        
        return modelAndView;
    }
    
    /**
     * @param settlement
     * @return
     */
    @RequestMapping(value = "/{coachId}/settlements/{settlementId}", method = RequestMethod.PATCH)
    public @ResponseBody String onEditSettlements(@Preloading("settlementId") CoachSettlement settlement) {
        
        Result result = new Result();
        
        try {
            
            coachService.editSettlement(settlement);
            
            result.success().message("更改教练基础工资成功");
            
        } catch (Exception e) {
            
            logger.error("#onEditSettlement - ", e);
            
            result.fail().message("更改教练基础工资失败");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * View principal branch management page
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/relations", method = RequestMethod.GET)
    public ModelAndView relations(@PathVariable("id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("system/principal/principal-report-relations");
        
        // get relations for the coach
        Principal principal = principalService.load(Principal.class, id);
        List<PrincipalReportRelation> relations = principalService.listRelation(principal);
        
        modelAndView.addObject("coachId", id);
        modelAndView.addObject("managerIds", CollectionUtils.extractPropertyList(relations, "manager.idString"));
        
        return modelAndView;
    }
    
    /**
     * On bind site
     * 
     * @param id
     * @param relationIds
     * @return
     */
    @RequestMapping(value = "/{id}/relations", method = RequestMethod.PATCH)
    public @ResponseBody String onEditRelations(@PathVariable("id") Long id,
                                                @RequestParam("relationIds") List<Long> relationIds) {
        
        Result result = new Result();
        
        try {
            
            Principal coach = principalService.load(Principal.class, id);

            // edit relation for the coach
            principalService.editRelation(coach, relationIds);
            
            result.success().message("更改教练汇报关系成功");
            
        } catch (Exception e) {
            
            logger.error("#onEditBranches - ", e);
            result.fail().message("更改教练汇报关系失败");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/change-site", method = RequestMethod.GET)
    public ModelAndView changeSite(@PathVariable("id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("system/principal/principal-site-change");
        
        // get relations for the coach
        Principal principal = principalService.load(Principal.class, id);
        PrincipalReportRelation relation = principalService.loadRelation(principal);
        
        modelAndView.addObject("principalId", id);
        modelAndView.addObject("relation", relation);
        
        return modelAndView;
    }
    
    @RequestMapping(value = "/{id}/change-site", method = RequestMethod.PATCH)
    public @ResponseBody String onChangeSite(@PathVariable("id") Long id,
                                             @RequestParam("siteId") Long siteId) {
        
        Result result = new Result();
        
        try {
            
            Principal principal = principalService.load(Principal.class, id);
            
            Site site = siteService.load(siteId);

            principalService.changeSite(principal, site);
            
            result.success().message("指定门店成功");
            
        } catch (Exception e) {
            
            logger.error("#onChangeSite - ", e);
            result.fail().message("指定门店失败");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
}
